<template>
	<view>
		<u-tabs :list="tabBars" line-width="120" :scrollable="false" :current="activeTab" @change="changeTab"></u-tabs>
		<view class="detail" v-if="showDetail">
			<view v-if="activeTab == 0">
				<defect-content :data="formData" :nfcData="nfcData" :isNew="isNew" :isEdit="isEdit" 
					:isView="isView" :isApprove="isApprove" :defaultData="defaultData" :editData="editData" 
					:disableData="disableData" @changeDfType="getFlowConfig">
				</defect-content>
			</view>
			<view v-if="activeTab == 1">
				<template v-if="isNew || isEdit || isApprove && editData.includes('app_base')">
					<attach-file :attachFile="formData.fileSet" :canEdit="true" businessCode="oh" 
						subBusinessCode="df" businessDataCode="df_mgt" @fileSet="fileSet">
					</attach-file>
				</template>
				<template v-else>
					<attach-file :attachFile="formData.fileSet"></attach-file>
				</template>
			</view>
		</view>
		<view v-if="!isView">
			<view class="button-groups" v-if="isNew || isEdit">
				<button type="primary" @click="saveData">{{$t('baseCommon.buttons.save')}}</button>
				<button type="primary" @click="startFlow" :disabled="startButtonFlag">{{$t('baseCommon.buttons.submit')}}</button>
			</view>
			<view v-else-if="isMore">
				<view class="button-more">
					<view class="btn-first btn-long">
						<button type="primary" v-for="(button, index) in buttons" :key="index" @click="handleBtn(button)">
							{{ button.name }}
						</button>
					</view>
					<view class="btn-second btn-short" @click="showMoreBtns">
						<button type="primary">
							<uni-icons type="more-filled" color="#fff" size="32"></uni-icons>
						</button>
					</view>
				</view>
				<view class="button-tooltip" v-show="showTooltip" @click="hideToolTip">
					<uni-list :border="false">
						<block v-for="(button, index) in moreBtns" :key="index">
							<uni-list-item :title="button.name" :showArrow="false" :show-extra-icon="true"
								:extra-icon="btnIcon[button.key]" :clickable="true" @click="handleBtn(button)">
							</uni-list-item>
						</block>
					</uni-list>
				</view>
			</view>
			<view :class="buttons.length > 2 ? 'button-groups-more' : 'button-groups'" v-else>
				<button type="primary" v-for="(button, index) in buttons" :key="index" @click="handleBtn(button)">
					{{ button.name }}
				</button>
			</view>
		</view>
		
		<!-- 审批意见弹出框 -->
		<uni-popup ref="opinion">
			<opinion-content :type="flowBtn.key" @handleFlow="handleFlow"></opinion-content>
		</uni-popup>
		
		<!-- 申请延期弹出框 -->
		<uni-popup ref="delay">
			<delay-content 
				:data="record" 
				:planEndTime="formData.planEndTime" 
				:operationTeamNo="formData.operationTeamNo"
				@getRecord="getRecord"
				@close="closePopup">
			</delay-content>
		</uni-popup>
		
		<!-- 申请挂起弹出框 -->
		<uni-popup ref="hang">
			<hang-content 
				:data="record"
				:operationTeamNo="formData.operationTeamNo"
				@getRecord="getRecord"
				@close="closePopup">
			</hang-content>
		</uni-popup>
		
		<!-- 转二三类弹出框 -->
		<uni-popup ref="transfer">
			<transfer-content 
				:data="record"
				:levelNo="formData.dfLevelNo"
				:operationTeamNo="formData.operationTeamNo"
				@getRecord="getRecord"
				@close="closePopup">
			</transfer-content>
		</uni-popup>
		
		<!-- 转专业弹出框 -->
		<uni-popup ref="major">
			<major-content 
				:data="record"
				:skillNo="formData.skillNo"
				:mtnPerson="formData.mtnPerson"
				:mtnTeamName="formData.mtnTeamName"
				:operationTeamNo="formData.operationTeamNo"
				@getRecord="getRecord"
				@close="closePopup">
			</major-content>
		</uni-popup>
	</view>
</template>

<script>
	import defectContent from "./components/detail-content.vue"
	import opinionContent from "@/components/base/opinion-popup.vue"
	import delayContent from "../components/delay-content.vue"
	import hangContent from "../components/hang-content.vue"
	import transferContent from "../components/transfer-content.vue"
	import majorContent from "./components/major-content.vue"
	import {
		getDefectInfo, 
		getDefectInfoByNo,
		updateDefectStatus, 
		getApproveOperateInfo, 
		addDefect, 
		addAndOrder, 
		addChangeRecord, 
		addChangeApproveRecord, 
		getNotifierByLevel,
		changeMajor,
		getFlowConfig
	} from '@/api/business/defect.js'
	import { notice, utilities } from '@/utils/common.js'
	import { saveInnerMessage } from '@/api/platform/common.js'
	import { getScheduleDate } from '@/api/business/shiftduty.js'
	import { saveTaskInspDfNo } from '@/api/business/inspect.js'
	import { getWorkTicketDetail } from '@/api/business/ticket.js'
	import { getConectInfoApi, getDataMaterialsApi } from '@/api/business/workorder.js'
	import ActionMixin from '@/utils/action.js'
	import NFCMixin from '@/utils/business/businessNFC.js'
	
	export default {
		mixins: [
			ActionMixin,
			NFCMixin
		],
		data() {
			return {
				// 流程变量，每个页面必须定义
				formData: {
					analysisTime: "",
					analysiser: "",
					analysiserId: "",
					assetId: "",
					assetName: "",
					assetNo: "",
					assetTypeId: "",
					attachFile: "",
					companyCode: "",
					companyName: "",
					createTime: "",
					createUser: "",
					dfCategory: "",
					dfClassification: "",
					dfDesp: "",
					dfId: "",
					dfLevelNo: "",
					dfNo: "",
					dfType: "",
					evaluateDesc: "",
					faultReasonDesc: "",
					faultReasonId: "",
					faultSchemeDesc: "",
					faultSchemeId: "",
					faultSymptonDesc: "",
					faultSymptonId: "",
					findTeamName: "",
					findTeamNo: "",
					finddate: "",
					findperson: "",
					findpersonId: "",
					finishTime: "",
					isReplace: 0,
					locaId: "",
					locaNo: "",
					locaName: "",
					manageObjName: "",
					manageObjNo: "",
					mtnPerson: "",
					mtnPersonId: "",
					mtnTeamName: "",
					mtnTeamNo: "",
					noticeperson: "",
					noticepersonId: "",
					oldEqTypeId: "",
					oldEqTypeName: "",
					oldStdWoId: "",
					oldStdWoName: "",
					oldFaultCode: "",
					oldFaultDescription: "",
					oldReasonAnalysis: "",
					oldTreatmentMeasure: "",
					operationTeamNo: "",
					operationTeamName: "",
					phenomenonId: "",
					phenomenonName: "",
					planEndTime: "",
					remark: "",
					skillNo: "",
					state: "",
					turnFinishTime: "",
					turnLevel: "",
					updateTime: "",
					updateUser: "",
					validateTime: "",
					validateUserId: "",
					validateUserName: "",
					woId: null,
					changeList: []
				},
				// 默认数据
				defaultData: {
					userId: '',
					userName: '',
					date: '',
					dateTime: ''
				},
				// 不展示字段
				disableData: [
					"app_fold", "app_accept", "app_change", "oldFaultDescription", "oldReasonAnalysis",
					"oldTreatmentMeasure", "oldStdWoName", "noticeperson", "isDefect", "finishTime",
					"clearDate", "validateUserName", "validateTime", "evaluateDesc", "wtWorkTktInv", "ysxx",
					"chooseTimeType"
				],
				// 可编辑字段
				editData: ["app_base"],
				// 初始赋值字段
				initData: [],
				// 校验字段
				requireData: [],
				startButtonFlag: false,
				// 必须字段end
				
				startFlowParam: {},
				tabBars: [
					{name: this.$t('baseCommon.other.baseInfo'), id: '0'},
					{name: this.$t('baseCommon.other.attachInfo'), id: '1'}
				],
				activeTab: 0,
				showDetail: false,
				dfId: '',
				dfNo: '',
				listIndex: 0,
				source: '',
				sourceId: '',
				sourceData: {},
				sourceType: '',
				showTooltip: false,
				btnIcon: {
					delay: {
						color: '#000000',
						size: '20',
						type: 'paperplane'
					},
					hang: {
						color: '#000000',
						size: '20',
						type: 'locked'
					},
					transfer: {
						color: '#000000',
						size: '20',
						type: 'loop'
					},
					delegate: {
						color: '#000000',
						size: '20',
						type: 'redo'
					},
					major: {
						color: '#000000',
						size: '20',
						type: 'refresh'
					},
					agree: {
						color: '#000000',
						size: '20',
						type: 'checkbox'
					},
					accept: {
						color: '#000000',
						size: '20',
						type: 'checkbox'
					}
				},
				connectInfoList: [],
				workTicketList: [],
				materialList: [],
				message: {
					canreply: 0,
					content: "",
					createBy: uni.getStorageSync("userId"),
					createTime: "",
					dataStatus: "1",
					dbType: "",
					durationTime: "",
					fileMsg: "",
					groupId: "",
					groupName: "",
					isPublic: 0,
					messageType: "system",
					name: "缺陷",
					ownerId: uni.getStorageSync("userId"),
					ownerName: uni.getStorageSync("userName"),
					receiver: " ",
					receiverId: "",
					receiverTime: "",
					subject: "设备缺陷管理审批抄送",
					updateBy: uni.getStorageSync("userId"),
					updateTime: ""
				},
				record: {
					applyTime: utilities.getNowDateTime(),
					applyedMeasure: "",
					applyer: uni.getStorageSync("userId"),
					applyerName: uni.getStorageSync("userName"),
					changeDesp: "",
					changeTime: "",
					changeType: "",
					dfId: "",
					risk: "",
					toLevel: "",
					toTeamNo: "",
					toTeamName: "",
					toUserId: "",
					toUserName: ""
				},
				approve: {
					approveTime: utilities.getNowDateTime(),
					approver: uni.getStorageSync("userId"),
					approverName: uni.getStorageSync("userName"),
					changeType: "",
					dfId: "",
					isApproved: 0,
					opinion: "通过"
				},
				isNew: false,
				isEdit: false,
				isView: false,
				isApprove: false,
				nfcData: ''
			}
		},
		components:{
			defectContent,
			opinionContent,
			delayContent,
			hangContent,
			transferContent,
			majorContent
		},
		onLoad(option) {
			// 初始化操作类型
			this.isNew = option.type === "add"
			this.isEdit = option.type === "edit"
			this.isView = option.type === "view"
			this.isApprove = option.type === "approve"
			
			this.dfId = option.dfId ? option.dfId : ""
			this.dfNo = option.dfNo ? option.dfNo : "" // 主要用于巡检查看缺陷
			this.sourceType = option.sourceType ? option.sourceType : ""
			
			if(option.source){
				this.source = option.source //数据来源
				this.sourceId = option.sourceId //数据来源id
				this.sourceData = JSON.parse(option.sourceData)
			}
			
			if(this.isNew || this.isEdit) {
				this.listIndex = 1
			}
			
			// #ifdef APP-PLUS
			this.listenNFCStatus()
			this.readyRead = true
			// #endif
			
			this.init()
			
			// 业务操作日志
			let operateType, operateKey;
			if(this.isNew) {
				operateType = 'add'
				operateKey = ''
			} else if(this.isEdit) {
				operateType = 'edit'
				operateKey = this.dfId
			} else {
				operateType = 'detail'
				operateKey = this.dfId
			}
			this.$saveOpLog(operateType, 'df_mgt', operateKey)
		},
		onUnload() {
			this.readyRead = false
		},
		methods: {
			async init() {
				// 初始化默认数据
				this.loadDefaultData()
				this.defaultData.isReasonAnalysis = true
				
				// 创建的话,需要初始化数据
				if (this.isNew) {
					this.formData.dfClassification = 'fire'
					this.formData.state = 'draft'
					this.formData.dfType = '1'
					this.formData.createTime = this.defaultData.dateTime
					this.formData.createUser = this.defaultData.userId
					this.formData.finddate = this.defaultData.dateTime
					this.formData.findperson = this.defaultData.userName
					this.formData.findpersonId = this.defaultData.userId
					this.formData.findTeamNo = uni.getStorageSync("userOrgId")
					this.formData.findTeamName = uni.getStorageSync("userOrgName")
					this.formData.companyCode = uni.getStorageSync("companyId")
					this.formData.companyName = uni.getStorageSync("companyName")
					
					switch (this.source) {
						case 'xundianjian': //巡点检
							this.formData.locaId = this.sourceData.locaId //设备位置id
							this.formData.locaNo = this.sourceData.locaNo //设备位置no
							this.formData.locaName = this.sourceData.locaName //设备位置名称
							this.formData.companyCode = this.sourceData.companyCode //场站
							this.formData.fileSet = this.sourceData.attachFile
							this.formData.dfDesp = this.sourceData.dfDesp || '' //缺陷描述
							break;
						case 'woFault': //风机故障登记缺陷
							this.formData.locaId = this.sourceData.locaId //设备位置id
							this.formData.locaNo = this.sourceData.locaNo //设备位置no
							this.formData.locaName = this.sourceData.locaName //设备位置名称	
							this.formData.dfType = this.sourceData.dfType
							this.formData.dfDesp = this.sourceData.dfDesp || '' //缺陷描述
							this.formData.dfLevelNo = this.sourceData.dfLevelNo || '' //缺陷等级
							this.formData.phenomenonId = this.sourceData.phenomenonId || '' //缺陷现象
							this.formData.companyCode = this.sourceData.companyCode || '' //场站
							break;
						case 'sisAlarm': //sis告警信息登记缺陷
							this.formData.locaId = this.sourceData.locaId //设备位置id
							this.formData.locaNo = this.sourceData.locaNo //设备位置no
							this.formData.locaName = this.sourceData.locaName //设备位置名称
							this.formData.dfDesp = this.sourceData.alarmDesc || '' //缺陷描述
							break;
					}
				} else {
					// 缺陷基本信息
					if(this.dfNo) {
						await getDefectInfoByNo(this.dfNo).then(res=>{
							this.dfId = res.data.dfId
							this.formData = res.data
						})
					} else {
						await getDefectInfo(this.dfId).then(res=>{
							this.formData = res.data
						})
					}
					// 缺陷变更信息
					await getApproveOperateInfo(this.dfId, '').then(res=>{
						this.formData.changeList = res.data.changeList
					})
					if(this.formData.woId) {
						// 缺陷物资信息
						getDataMaterialsApi({ woId: this.formData.woId }).then(res=>{
							this.materialList = res.data
						})
						// 缺陷关联信息
						this.getconnectInfoList()
					}
				}
				
				// 流程初始字段设置
				if(this.isNew || this.isEdit) {
					this.getFlowConfig()
				}
				
				// 流程信息
				if(this.isApprove) {
					await this.getFlowTaskInfo(this.dfId)
					// 初始化数据
					this.loadInitData()
				}
				
				// 显示全部字段
				if(this.isView) {
					this.disableData = []
				}
				
				// 页面标题
				uni.setNavigationBarTitle({
				　　title: this.isView ? this.$t('common.buttons.see') : (this.isNew || this.isEdit) ? this.$t('defect.state.defReg') : this.nodeName
				})
				
				this.showDetail = true
			},
			async getFlowConfig() {
				await getFlowConfig(this.formData.dfType).then(async res => {
					if(res.data) {
						this.startFlowParam.defKey = res.data.bindBusinessObject,
						this.startFlowParam.flowKey = res.data.flowKey
						
						// 初始化脚本
						await this.handleScrpitData(this.startFlowParam.flowKey)
						// 初始化数据
						await this.loadInitData()
					}
				})
			},
			// 获取缺陷关联信息
			getconnectInfoList() {
				getConectInfoApi({ woId: this.formData.woId }).then(res=>{
					res.data.forEach(item=>{
						// 关联信息过滤工作票、领料单、退料单
						if(item.boTypeNo == 'wt_wt' || item.boTypeNo == 'ex_mat_use' || item.boTypeNo == 'ex_mat_gb') {
							item.value = item.boNo + "-" + item.boContent
							this.connectInfoList.push(item)
						}
						// 主要用于申请验收时校验工作票是否完结
						if(item.boTypeNo == 'wt_wt') {
							getWorkTicketDetail(item.boId).then(res=>{
								this.workTicketList.push(res.data)
							})
						}
					})
				})
			},
			changeTab(e) {
				this.activeTab = e.index
			},
			saveData() {
				if(!this.validateForm()){
					return;
				}
				
				addDefect(this.formData).then(res=>{
					if(res.code === 0) {
						uni.showToast({
							title: this.$t('defect.message.defectRegisterSuccess'),
							duration: 500
						});
						
						if(null !== this.sourceId && '' !== this.sourceId) {
							this.saveSourceData(res.data.dfId)
						}
						
						if(this.source) {
							const eventChannel = this.getOpenerEventChannel();
							eventChannel.emit('eventData', '');
							uni.navigateBack()
						} else {
							utilities.back(this.sourceType, this.listIndex)
						}
					}
				})
			},
			async start() {
				const _this = this
				if(!_this.validateForm()){
					return;
				}
				uni.showModal({
					title: _this.$t('baseCommon.message.tips'),
					content: _this.$t('defect.message.sureStartProcess'),
					success: function (res) {
						if (res.confirm) {
							_this.startButtonFlag = true
							if(_this.startFlowTotal === 1) {
								// 保存数据
								addDefect(_this.formData).then(res=>{
									if(!_this.dfId){
										_this.dfId = res.data.dfId
									}
									
									if(null !== _this.sourceId && '' !== _this.sourceId) {
										_this.saveSourceData()
									}
									
									// 启动流程
									_this.flowStart(_this.dfId, _this.startFlowParam.defKey, _this.startFlowParam.flowKey).then(res => {
										if(res === 200) {
											if(_this.source) {
												const eventChannel = _this.getOpenerEventChannel();
												eventChannel.emit('eventData', '');
												uni.navigateBack()
											} else {
												utilities.back(_this.sourceType, _this.listIndex)
											}
										}
									})
								})
							}
						} else {
							_this.startFlowTotal = 0
							_this.startButtonFlag = false
						}
					}
				})
			},
			handleBtn(button) {
				this.flowBtn = button
				this.showTooltip = false
				if(this.flowBtn.key == 'oppose') {
					// 审批意见
					this.$refs.opinion.open()
				} else {
					// 表单校验
					if(this.validateFlow()) {
						// 消缺-申请验收
						if(this.flowBtn.key == 'accept') {
							this.applyAccept()
						}
						// 消缺-申请延期
						else if(this.flowBtn.key == 'delay') {
							this.applyDelay()
						}
						// 消缺-申请挂起
						else if(this.flowBtn.key == 'hang') {
							this.applyHang()
						}
						// 消缺-转二三类
						else if(this.flowBtn.key == 'transfer') {
							this.applyTransfer()
						}
						// 消缺-转专业
						else if(this.flowBtn.key == 'major') {
							this.applyMajor()
						}
						// 消缺-转办
						else if(this.flowBtn.key == 'delegate') {
							this.applyDelegate()
						}
						// 修改挂起原因
						else if(this.flowBtn.key == 'editHang') {
							this.editHangUp()
						}
						else {
							// 审批意见
							this.$refs.opinion.open()
						}
					}
				}
			},
			handleFlow(opinion) {
				this.$refs.opinion.close()
				this.opinion = opinion
				
				this.emitButtonEventHandler("agree")
				// this.emitButtonEventHandler(this.flowBtn.key)
			},
			// 保存表单
			saveForm(type) {
				if(!this.validateForm()){
					return;
				}
				
				if(type === 'add') {
					addDefect(this.formData)
				} else if(type === 'addAndOrder') {
					addAndOrder(this.formData)
				} else {
					addDefect(this.formData)
				}
			},
			// 更新状态
			updateState() {
				// addDefect(this.formData)
				updateDefectStatus(this.formData.dfId, this.formData.state)
			},
			// 更新表单
			async updteForm(targetField) {
				if(targetField == 'dfLevelNo') {
					await getNotifierByLevel(this.formData[fromField]).then(res=>{
						let timeLimit = res.data.split("--")[2]
						this.formData.planEndTime = utilities.getCalDateTime(this.formData.finddate, timeLimit)
					})
				}
				addDefect(this.formData)
			},
			// type,类型：removeHang,add,sub
			resetTime(type, fieldTime, targetFieldTime, hours) {
				if(type == 'removeHang') {
					if(this.formData.chooseTimeType == '1') {
						getNotifierByLevel(this.formData.dfLevelNo).then(res => {
							let cur = new Date()
							if (res.data != null && res.data !== '') {
								try {
									var timelimit = ~~(res.data.split('--')[2])
									cur = new Date(cur.getTime() + (timelimit * 60 * 60 * 1000))
									this.formData.planEndTime = utilities.formatDate(cur, 'yyyy-MM-dd HH:mm:ss')
									addDefect(this.formData)
								} catch(e) {
									console.info(e)
								}
							}
						})
					} else if(this.formData.chooseTimeType == '2') {
						this.formData.planEndTime = null
						addDefect(this.formData)
					}
				}
				if(type == 'add' || type == 'sub') {
					let cur = new Date()
					if(targetFieldTime.indexOf('formData') != -1) {
						targetFieldTime = targetFieldTime.replace(/formData./g, '')
						if(fieldTime.indexOf('formData') != -1) {
							fieldTime = fieldTime.replace(/formData./g, '')
							if(type == 'add') {
								cur = new Date(this.formData[fieldTime].getTime() + (hours * 60 * 60 * 1000))
							} else {
								cur = new Date(this.formData[fieldTime].getTime() - (hours * 60 * 60 * 1000))
							}
						} else if(fieldTime.indexOf('defaultData') != -1) {
							fieldTime = fieldTime.replace(/defaultData./g, '')
							if(type == 'add') {
								cur = new Date(this.defaultData[fieldTime].getTime() + (hours * 60 * 60 * 1000))
							} else {
								cur = new Date(this.defaultData[fieldTime].getTime() - (hours * 60 * 60 * 1000))
							}
						}
						this.formData[targetFieldTime] = utilities.formatDate(cur, 'yyyy-MM-dd HH:mm:ss')
						addDefect(this.formData)
					}
				}
			},
			validateForm() {
				var formFlag = true
				if(!this.formData.locaName){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.common.locaName') }))
					formFlag = false
				}
				if(!this.formData.dfLevelNo){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.common.defectLev') }))
					formFlag = false
				}
				if(!this.formData.dfType){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.dfType') }))
					formFlag = false
				}
				if(!this.formData.dfDesp){
					notice.toast(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('defect.common.defectCom') }))
					formFlag = false
				}
				if(!this.formData.findperson){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.findperson') }))
					formFlag = false
				}
				if(!this.formData.mtnTeamName) {
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.mtnTeamName') }))
					formFlag = false
				}
				return formFlag
			},
			validateFlow() {
				var formFlag = true
				let that = this
				for (const [key, rules] of Object.entries(that.requireData)) {
					// 必输校验
					if(rules.required && that.formData.hasOwnProperty(key) && !that.formData[key]) {
						notice.toast(rules.message)
						formFlag = false
						break
					}
				}
				return formFlag
			},
			// 申请验收校验
			validatesqys() {
				var flag = true
				let someNotFinished = this.workTicketList.some(link =>
					!["end", "qualified", "unqualified", "abolished", ].includes(link.state))
				if (someNotFinished) {
					notice.toast(this.$t('defect.message.unfinishedWorkTicket'))
					flag = false
				}
				if(!this.formData.maintenanceExplain){
					notice.toast(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('defect.defInfo.maintenanceExplain') }))
					flag = false
				}
				return flag
			},
			// 缺陷验收校验
			validateqxys() {
				if(!this.formData.finishTime){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.finishTime') }))
					throw new Error(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.finishTime') }))
				}
				if(!this.formData.clearDate){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.clearTime') }))
					throw new Error(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.clearTime') }))
				}
				if(!this.formData.evaluateDesc){
					notice.toast(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('defect.defInfo.evaluateDesc') }))
					throw new Error(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('defect.defInfo.evaluateDesc') }))
				}
			},
			// 申请验收
			applyAccept() {
				if(this.validatesqys()) {
					this.formData.clearDate = utilities.getNowDateTime()
					
					this.record.dfId = this.dfId
					this.record.changeTime = this.formData.clearDate
					this.record.changeDesp = this.formData.maintenanceExplain
					
					this.$refs.opinion.open()
				}
			},
			// 申请延期
			applyDelay() {
				this.$refs.delay.open()
			},
			// 申请挂起
			applyHang() {
				this.$refs.hang.open()
			},
			// 转二三类
			applyTransfer() {
				this.$refs.transfer.open()
			},
			// 转专业
			applyMajor() {
				this.$refs.major.open()
			},
			// 转办
			applyDelegate() {
				uni.navigateTo({
					url: '/pages/platform/common/delegate?type=defect&taskId=' + this.taskId + '&bizKey=' + this.dfId
				})
			},
			// 修改挂起原因
			editHangUp() {
				let hangList = this.formData.changeList.filter(r => r.changeType == 'gqsq')
				if(hangList.length > 0){
					hangList.sort((a,b) => new Date(b.applyTime).getTime() - new Date(a.applyTime).getTime())
					Object.assign(this.record, hangList[0])
				}
				this.$refs.hang.open()
			},
			showMoreBtns() {
				this.showTooltip = true
			},
			hideToolTip() {
				this.showTooltip = false
			},
			addChangeRecord() {
				this.record.changeType = this.variableMap.DEFECT_SELECT
				addChangeRecord(this.record)
			},
			addChangeApproveRecord(type, isAgree) {
				this.approve.dfId = this.dfId
				this.approve.isApproved = isAgree ? 0 : 1
				this.approve.opinion = this.opinion
				this.approve.changeType = type
				addChangeApproveRecord(this.approve)
			},
			closePopup(type) {
				this.$refs[`${type}`].close()
				if(type == "hang" && this.flowBtn.key == "editHang") {
					this.showDetail = false
					this.addChangeRecord()
					this.init()
					setTimeout(() => {
						this.showDetail = true
					}, 200)
				} else {
					if(type == "delay"){
						this.formData.turnFinishTime = this.record.changeTime
					}
					if(type == "transfer"){
						this.formData.turnLevel = this.record.toLevel
					}
					this.opinion = this.$t('common.buttons.agree')
					this.emitButtonEventHandler("agree")
				}
			},
			reciveUser(type, data) {
				let params = {
					users: data,
					isSelect: "N",
					isSubFlow: true
				}
				if(type == "delay"){
					this.formData.turnFinishTime = this.record.changeTime
				}
				if(type == "transfer"){
					this.formData.turnLevel = this.record.toLevel
				}
				
				this.opinion = this.$t('common.buttons.agree')
				this.emitButtonEventHandler("agree")
			},
			sendMessage() {
				let userid = uni.getStorageSync("userId")
				let username = uni.getStorageSync("userName")
				let datetime = utilities.getNowDateTime()
				let status = this.formData.dfLevelNo == "1" ? this.$t('defect.state.appPlan') : this.$t('defect.state.DefElimination')
				
				this.message.receiver = this.formData.noticeperson
				this.message.receiverId = this.formData.noticepersonId
				this.message.receiverTime = datetime
				this.message.createTime = datetime
				this.message.updateTime = datetime
				this.message.content = "设备缺陷管理审批抄送，"+username+"在"+datetime+"发起的设备缺陷流程<a href=javascript:link >"+this.formData.dfNo+"</a>(缺陷描述："+this.formData.dfDesp+")已到<"+status+">状态"
				saveInnerMessage(this.message)
				
				utilities.back(this.sourceType, this.listIndex)
			},
			changeMajorFn(type) {
				if(type == 'nbbg'){
					let changeData = this.formData.changeList.filter(one => one.changeType == 'nbbg')
					if(changeData != null){
						changeData.sort((a,b) => new Date(b.applyTime).getTime() - new Date(a.applyTime).getTime())
						this.formData.mtnTeamNo = changeData[0].toTeamNo
						this.formData.mtnTeamName = changeData[0].toTeamName
					}
				}
				changeMajor(this.formData.dfId, type)
			},
			getRecord(data) {
				this.record.dfId = this.dfId
				Object.assign(this.record, data)
			},
			saveSourceData(dfId) {
				// 巡检表dfNo字段改为存缺陷表dfId字段
				if('xundianjian' === this.source) { //巡点检
					let data = {
						taskInspId: this.sourceId,
						dfNo: dfId,
						isAbnormalHandled: 1,
						handlingMemo: this.$t('defect.message.transferredDefect')
					}
					saveTaskInspDfNo(data) //更新巡点检
				}
				// getDefectInfo(dfId).then(res=>{
				// 	if('xundianjian' === this.source) { //巡点检
				// 		let data = {
				// 			taskInspId: this.sourceId,
				// 			dfNo: res.data.dfNo,
				// 			handlingMemo: "已转消缺"
				// 		}
				// 		saveTaskInspDfNo(data) //更新巡点检
				// 	}
				// })
			},
			resetMaterial(data) {
				this.materialList = JSON.parse(JSON.stringify(data));
			},
			fileSet(data) {
				this.formData.fileSet = data
			}
		},
		onNavigationBarButtonTap() {
			if (this.isNew || this.isEdit || this.formData.state == 'draft') {
				notice.toast(this.$t('defect.message.processHasNotStarted'))
				return false
			}
			uni.navigateTo({
				url: '/pages/base/flow/flow-history?bizKey=' + this.formData.dfId + "&defKey=" + this.procDefKey
			})
		},
		onBackPress(options) {
			setTimeout(()=>{
				utilities.backQuick(this.sourceType == 'offline' ? this.sourceType : 'back')
			}, 10);
		}
	}
</script>

<style lang="scss">
	@import '@/static/style/common-detail.scss';
</style>
<style lang="scss" scoped>
	.detail {
		padding-top: 8px;
	}
	
	.fileinfo {
		padding: 12px 8px;
	}
	
	/deep/ .uni-list-item__content-title {
		text-align: center;
	}
</style>
